package com.wenhao.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Wenhao Tong
 * @create 2021-08-19 17:21
 */
public class ProviderAndConsumerOrder {
    public static void main(String[] args) {
        Data3 data = new Data3();

        new Thread(() -> {
            for (int i = 0;i < 10;i++) {
                try {
                    data.printA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0;i < 10;i++) {
                try {
                    data.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0;i < 10;i++) {
                try {
                    data.printC();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
    }
}

class Data3 {
    private int number = 0;

    Lock lock = new ReentrantLock();
    /**
     * 多个同步监视器，每一个去管理一个线程
     */
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void printA() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                condition1.await();
            }
            number++;
            System.out.println("A");
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void printB() throws InterruptedException {
        lock.lock();
        try {
            while (number != 1) {
                condition2.await();
            }
            number++;
            System.out.println("B");
            // 精确唤醒
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void printC() throws InterruptedException {
        lock.lock();
        try {
            while (number != 2) {
                condition3.await();
            }
            number = 0;
            System.out.println("C");
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
}
